﻿using AutoMapper;
using MediatR;
using Product.API.Applcation.Command.Product;
using Product.Domain;
using Product.Infrstructre.Impl;

namespace Product.API.Applcation.CommandHandlers.Product
{
    /// <summary>
    /// 产品添加
    /// </summary>
    public class ProductInfoCommandHandler : IRequestHandler<ProductInfoCommand, int>
    {
        protected readonly IbaseProductInfoRepository ibaseProductInfo;
        protected readonly IMapper mapper;

        public ProductInfoCommandHandler(IbaseProductInfoRepository ibaseProductInfo, IMapper mapper)
        {
            this.ibaseProductInfo = ibaseProductInfo;
            this.mapper = mapper;
        }

        public async Task<int> Handle(ProductInfoCommand request, CancellationToken cancellationToken)
        {
            var newProduct = (await ibaseProductInfo.GetAllAsync()).Where(x => x.ProductsName == request.addDTO.ProductsName || x.ProductsCode == request.addDTO.ProductsCode);
            if (newProduct.Count() > 0)
            {
                return -1;
            }
            else
            {
                return await ibaseProductInfo.AddAsync(mapper.Map<Products>(request.addDTO));
            }

        }
    }
}
